//
//  YHPSoundPlayTools.m
//  AVDemo2
//
//  Created by Yan on 16/3/22.
//  Copyright © 2016年 baidu. All rights reserved.
//

#import "SoundPlayTools.h"
#import <AVFoundation/AVFoundation.h>

// 单利
static NSMutableDictionary  *cacheDict;

@implementation SoundPlayTools

/***
 注释:
 * 1. 获取资源url 
 * 2. 定义一个soundID 创建一个soundID
 * 3. 播放音效
 ***/

// 类初始化时调用一次
+(void)load {
    cacheDict = [NSMutableDictionary dictionary];
}

+(void)playSoundWithFileName:(NSString *)filename isAlert:(BOOL)isAlert {
    
    if (![cacheDict[filename] unsignedIntValue]) {
        
    
// 加载本地文件
        NSURL * url = [[NSBundle mainBundle]URLForResource:filename withExtension:nil];
// typedef UInt32      SystemSoundID;
// 定义
        SystemSoundID soundID;
// 创建  音效服务创建系统soundID
/***
 注释:
 * 1. 文件路径
 * 2. soundID地址
 * 3.
 ***/
        AudioServicesCreateSystemSoundID((__bridge CFURLRef _Nonnull)(url), &soundID);

        cacheDict[filename] = @(soundID);
    }
    
    SystemSoundID soundID = [cacheDict[filename] unsignedIntValue];
    NSLog(@"%d",soundID);
    
    /***
     注释:
     * 1. 在静态区创建一个字典
     * 2. 将soundID以filename作为键存入字典
     * 3. 实例化soundID时使用value for key
     ***/
    /*
     *2016-03-22 22:30:59.947 AVDemo2[1906:27302] 4097
     2016-03-22 22:31:06.155 AVDemo2[1906:27302] 4098
     2016-03-22 22:31:06.636 AVDemo2[1906:27302] 4099
     2016-03-22 22:31:06.827 AVDemo2[1906:27302] 4100
     2016-03-22 22:31:06.994 AVDemo2[1906:27302] 4101
     2016-03-22 22:31:07.144 AVDemo2[1906:27302] 4102
     2016-03-22 22:31:07.295 AVDemo2[1906:27302] 4103
     2016-03-22 22:31:07.453 AVDemo2[1906:27302] 4104
     2016-03-22 22:31:07.573 AVDemo2[1906:27302] 4105
     2016-03-22 22:31:07.775 AVDemo2[1906:27302] 4106
     */
    
    // 问题: 创建N多次soundID 怎么解决----> 单利
    // 2016-03-22 22:54:38.333 AVDemo2[2570:39049] 4097
    // 2016-03-22 22:54:41.974 AVDemo2[2570:39049] 4097

// 播放
    if (isAlert) {
        // 震动
            AudioServicesPlayAlertSound(soundID);
    } else {
        // 不震动
        AudioServicesPlaySystemSound(soundID);
    }
}

//清除缓存
+(void)clearMemary {
    for (NSString * key in cacheDict) {
        SystemSoundID soundID = [cacheDict[key]unsignedIntValue];
        
        AudioServicesDisposeSystemSoundID(soundID);
        [cacheDict removeAllObjects];
        NSLog(@"clear finish");
    }
}
@end
